package com.shengyuan.manage_os.old.ying.erpm;


import org.json.JSONException;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.shengyuan.manage_os.R;
import com.shengyuan.manage_os.im.common.utils.ToastUtil;
import com.shengyuan.manage_os.im.ui.LocationActivity;
import com.shengyuan.manage_os.im.ui.LocationInfo;
import com.shengyuan.manage_os.old.ying.boce.task.TaskParams;
import com.shengyuan.manage_os.old.ying.erpm.controls.CurrentPersonal;
import com.shengyuan.manage_os.old.ying.erpm.controls.CurrentTime;
import com.shengyuan.manage_os.old.ying.erpm.controls.GpsButton;
import com.shengyuan.manage_os.old.ying.erpm.controls.PictureButton;
import com.shengyuan.manage_os.old.ying.erpm.tasks.Submit_System_Setting_Data_Task;
import com.shengyuan.manage_os.old.ying.erpm.util.SoundControler;
import com.shengyuan.manage_os.old.ying.erpm.util.Utility;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;

import static com.baidu.location.LocationClientOption.LocationMode.Hight_Accuracy;

public class Actual_OA_DaKa_JiDong extends BaseActivity implements OnGetGeoCoderResultListener {
	public static Boolean HaveCreate= false;
	public static String nowTime = "";
	public static PendingIntent pi = null;
	public String DengJi, mUserName;
	protected PictureButton PictureButton_myself;
	protected EditText edit_where, edit_what, edit_nextstep;
	protected TextView textview_guidingtime;
	protected TableRow tablerow_guidingtime;
    LocationClient mLocClient;
	MapView mMapView;
	BaiduMap mBaiduMap;
	public static Boolean bShow= false;
	private Bundle msavedInstanceState;
	private TableRow row_question;
	//private Vibrator vibrator=null;
	
	private SoundControler sControler;

	@Override
	public void onClick(View view) {
		super.onClick(view);
		
	}
	
	private Boolean mVoice;;
	GestureDetector gdDetector ;
	private View viewCache;
	private TextView tvResult;


	private double lat;
	private double lon;
	private String address = "";
	GeoCoder mSearch = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		msavedInstanceState = savedInstanceState;

		if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS)) {
			ToastUtil.showMessage("您的手机没有GPS硬件");
			finish();
		}
		System.out.println("&&&&&&&&&&Actual_OA_DaKa_jidong");
		HaveCreate = true;
		setContentView(R.layout.actual_oa_daka_jidong);
		LinearLayout ll = (LinearLayout) findViewById(R.id.daka_backgroup);
		ll.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (sControler!=null) {
					sControler.Stop();
				}
				return false;
			}
		});
		//gdDetector = new GestureDetector(this, new MyGestureListener(this));
		mVoice = false;
		
		InitControls();
		row_question.setVisibility(View.GONE);
        if (getIntent().getExtras()!=null) {
			DengJi = getIntent().getStringExtra("DengJi");
            //Object o1 = getIntent().getExtras().get("GuiDing");
//            Object o2 = getIntent().getExtras().get("UserName");
//            if (o!=null) {
//    			DengJi = o.toString();
//    			mUserName = LoginActivity.pmUser.UserName;
//    		}else {
//				finish(); return;
//			}
//
//            if (o2!=null) {
//            	mUserName = o2.toString();
//			}
//            if (mUserName==null || mUserName=="") {
//				finish(); return;
//			}
//            CurrentPersonal.UserName = mUserName;
		}else {
			finish(); return;
		}

        sControler = new SoundControler(this);
        if (DengJi.contains("定位")) {
        	btn_back.setVisibility(View.GONE);
        	//屏蔽按钮
        	mVoice = true;
        	row_question.setVisibility(View.VISIBLE);
        	if (DengJi.contains("被动")) {
        		btn_back.setVisibility(View.GONE);
        	}
        	if (DengJi.contains("补打")) {
        		btn_back.setVisibility(View.VISIBLE);
			}else {
				sControler.Play(this);
			}
        	
//        	if (LoginActivity.pmUser==null) {
//				Utility.MessageBox(this,"主程序已经清除, 请启动管理程序");
//				Intent intent = new Intent();
//				intent.setClass( Actual_OA_DaKa_JiDong.this, LoginActivity.class );
//				startActivity(intent);
//				finish();
//			}else {
////				StartAlarm();
//			}
		}
        //Utility.MessageBox(DengJi);
        bShow = true;
		viewCache = LayoutInflater.from(this)
				.inflate(R.layout.pop_layout, null);
		tvResult = (TextView) viewCache.findViewById(R.id.location_tips);
		mSearch = GeoCoder.newInstance();
		mSearch.setOnGetGeoCodeResultListener(this);
		mMapView = (MapView) findViewById(R.id.bmapView);
		mBaiduMap = mMapView.getMap();
		mBaiduMap.setMyLocationEnabled(true);
		mLocClient = new LocationClient(this);
		mLocClient.registerLocationListener(new MyLocationListenner());
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setCoorType("bd09ll");
//		option.setAddrType("all");
		option.setIsNeedAddress(true);
		option.setIsNeedLocationDescribe(true);
		option.setLocationMode(Hight_Accuracy);
		option.setScanSpan(15*60*1000);
		mLocClient.setLocOption(option);
		mLocClient.start();
//		mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
//
//			@Override
//			public boolean onMapPoiClick(MapPoi arg0) {
//				// TODO Auto-generated method stub
//				return false;
//			}
//
//			@Override
//			public void onMapClick(LatLng latLng) {
//				double latitude = latLng.latitude;
//				double longitude = latLng.longitude;
//				mBaiduMap.clear();
//				LatLng point = new LatLng(latitude, longitude);
//
//				lat=latitude;
//				lon=longitude;
//				MarkerOptions options = new MarkerOptions().position(point)
//						.icon(com.baidu.mapapi.map.BitmapDescriptorFactory
//								.fromResource(R.drawable.icon_marka));
//				mBaiduMap.addOverlay(options);
//
//
//				ReverseGeoCodeOption op = new ReverseGeoCodeOption();
//				op.location(latLng);
//				mSearch.reverseGeoCode(op);
//
//			}
//		});
	}
	boolean isFirstLoc = true;
	public class MyLocationListenner implements BDLocationListener {

		private InfoWindow infoWindow;

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null || mMapView == null) {
				return;
			}
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(location.getRadius())
					.direction(100).latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			LatLng ll = null;
			GpsButton.pAMapLocation = location;
			address = location.getAddrStr()+"("+location.getLocationDescribe()+")";
			System.out.println("FFFFFFFFFF@MyLocationListenner===="+address);
			mBaiduMap.setMyLocationData(locData);
			if (isFirstLoc) {
				isFirstLoc = false;
				ll = new LatLng(location.getLatitude(), location.getLongitude());
				MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
				mBaiduMap.animateMapStatus(u);
			}

			if (ll != null) {
				lat=ll.latitude;
				lon=ll.longitude;
				mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(ll));

			}
		}

		public void onReceivePoi(BDLocation poiLocation) {
		}
	}


	@Override
	public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

	}

	@Override
	public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
		// TODO Auto-generated method stub

		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			return;
		}

		if(mBaiduMap==null){
			return;
		}

		tvResult.setText(address);
//		address=result.getAddress();
		InfoWindow infoWindow = new InfoWindow(viewCache, result.getLocation(),
				-90);
		mBaiduMap.showInfoWindow(infoWindow);
		System.out.println("FFFFFFFFFF@GeoCodeResult===="+address);
		MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(result.getLocation());


		mBaiduMap.animateMapStatus(u);

		mBaiduMap.addOverlay(new MarkerOptions()
				.position(result.getLocation())
				.title(result.getAddress())
				.icon(com.baidu.mapapi.map.BitmapDescriptorFactory
						.fromResource(R.drawable.icon_marka)));

	}

	
    @Override
	protected void onStop() {
		super.onStop();
		HaveCreate = false;
	}
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	//PlayMusic();
    	if (DengJi.contains("定位")) {
	    	if(keyCode == KeyEvent.KEYCODE_BACK) { //监控/拦截/屏蔽返回键
	    	return false; 
	    	} else if(keyCode == KeyEvent.KEYCODE_MENU) {
	    	return false;
	    	} else if(keyCode == KeyEvent.KEYCODE_HOME) {
	    	//由于Home键为系统键，此处不能捕获，需要重写onAttachedToWindow()
	    	return false;
	    	}
    	}
    	return super.onKeyDown(keyCode, event);
    }
	// 拦截/屏蔽系统Home键
//	public void onAttachedToWindow() {
//		try {
//			this.getWindow().setType(WindowManager.LayoutParams.);
//		} catch (Exception e) {
//		}
//		super.onAttachedToWindow();
//	}

	@Override
	protected void SaveJsonData() {
		try {
			JsonMyID();
			IsJson1 = true; mFinished = 1; mPrintenabled= 0;
			if (DengJi.equals("DengJiTime1")) {//开始巡查定位
				mJson.put( "类型",  "上班" );
				mPrintcount = 1; //为判 定 最后 是上班还是下班
				StartAlarm();
			}else if(DengJi.equals("DengJiTime2")){
				mJson.put( "类型",  "下班" );
				mPrintcount = 2;
				if (pi!=null) {//不再显示登记
					//ECApplication.mAlarmManager.cancel(pi);
				}
			}else {
				mPrintcount = 3;
				mJson.put( "类型",  DengJi );
				if (!DengJi.contains("被动")) {
					StartAlarm();
				}
			}
			
			getDataExt();

			mJson.put( getString(R.string.title_actual_form_editText_personal),  CurrentPersonal.UserName);
			mJson.put( getString(R.string.title_actual_form_currenttime),  CurrentTime.getLongTime() );		
			getMemo();
			JsonPicture_Ext();
			ShowMessage();
			SendGPS(GpsButton.pAMapLocation);
		}catch (Exception e) {
			System.out.println("++++++++Exception==="+e);
		}
	}

	public void SendGPS(BDLocation aLocation) {
		if (aLocation==null) {
			return;
		}
		Submit_System_Setting_Data_Task mSubmitTask = new Submit_System_Setting_Data_Task();
		//mSubmitTask.setListener(mTaskListener);
		TaskParams params;
		params = new TaskParams();
		params.put(Submit_System_Setting_Data_Task.TYPENAME, LocationActivity.class.toString());
		params.put(Submit_System_Setting_Data_Task.TYPECODE,
				LoginActivity.pmUser.UserName+","+  aLocation.getTime() +","+
						aLocation.getLongitude()+","+ aLocation.getLatitude());
		mSubmitTask.execute(params);
	}
	
	private void StartAlarm() {
		try {
			long now = System.currentTimeMillis();
			now = (long) (now + 1000 * 60 * 1 * 60) ;
			//SetAlarmActivity(now);		
			
			//vibrator=(Vibrator)getSystemService(Service.VIBRATOR_SERVICE);
		} catch (Exception e) {
		}

	}
	
	private void ShowMessage() {
		String str = LoginActivity.pmUser.UserName;
		int len = edit_what.getText().toString().length() + edit_nextstep.getText().toString().length();
		if (len>30) {
			if (edit_nextstep.getText().toString().length()>20) {
				str+= ",你非常优秀！考评分更多！";
			}else {
				str +=  ",你的工作很认真！继续努力加油！多奖励考评分！";
			}
		}else {
			str += "恭喜你！系统自动为你的考评加分了!";
		}
		Utility.MessageBox(this,str);
		System.out.println("++++++++showMessage==="+str);

	}
	
//	public void SetAlarmActivity(long now) {
//		try {
//			ECApplication.mAlarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
//			Intent intent =new Intent(ECApplication.Instance, Actual_OA_DaKa_JiDong.class);
//			intent.putExtra("DengJi", "定位");
//			intent.putExtra("GuiDing", now);
//			intent.putExtra("UserName", mUserName);
//			pi = PendingIntent.getActivity(ECApplication.Instance, 0,
//					intent, Intent.FLAG_ACTIVITY_NEW_TASK);
//			ECApplication.mAlarmManager.set(AlarmManager.RTC_WAKEUP, now, pi);
//		} catch (Exception e) {
//			Utility.MessageBox(e.getMessage());
//		}
//	}
//	
	protected void getDataExt() throws JSONException {
		String s = "";
		double x = lat;
		double y = lon;
		try {
			s = address;
		} catch (Exception e) {
		}
		mJson.put( getString(R.string.title_actual_form_GpsButton_Gps), s + "," + x + "," + y);
		System.out.println("++++++++現場位置==="+s + "," + x + "," + y);
		//mJson.put( getString(R.string.title_actual_oa_daka_guiding), GuiDing);
		if (edit_where!=null) {
			mJson.put( getString(R.string.title_actual_oa_daka_where), edit_where.getText().toString());
		}
		if (edit_what!=null) {
			mJson.put( getString(R.string.title_actual_oa_daka_what), edit_what.getText().toString());
		}
		if (edit_nextstep!=null) {
			mJson.put( getString(R.string.title_actual_oa_daka_nextstep), edit_nextstep.getText().toString());
		}
	}
	
	protected void JsonPicture_Ext() throws JSONException {
		if (PictureButton_myself!=null) {
			mJson.put( getString(R.string.title_actual_form_myself), PictureButton_myself.mFileName);
		}
	}	
	
	@Override
	protected void SaveSelfPic(String sPath) {
		try {
			CopyPicDest(PictureButton_myself, sPath);
		} catch (Exception e) {
			Utility.MessageBox(this,e.getMessage());
		}
	}

	@Override
	public void Back() {
		bShow = false;
		if (sControler!=null) {
			sControler.Stop();
		}
		super.Back();
	}

	@Override
	public void onBackPressed() {
		bShow = false;
		super.onBackPressed();
	}
	
	@Override
	public void InitControls() {
		super.InitControls();
		tablerow_guidingtime = (TableRow) findViewById(R.id.tablerow_guidingtime);
		textview_guidingtime =(TextView) findViewById(R.id.textview_guidingtime);
		PictureButton_myself = (PictureButton) findViewById(R.id.PictureButton_myself);
		
		row_question = (TableRow) findViewById(R.id.row_question);
		edit_where =(EditText) findViewById(R.id.editText_where);
		edit_what =(EditText) findViewById(R.id.editText_what);
		edit_nextstep  =(EditText) findViewById(R.id.editText_nextstep);
	}
	
	@Override
	public Boolean IsPassed() {
		if (sControler!=null) {
			sControler.Stop();
		}
		if (super.IsPassed()) {
			if (mVoice) {
				if (!CheckEditEmpty(edit_where)) {
					return false;
				}
				if (!CheckEditEmpty(edit_what)) {
					return false;
				}
				if (!CheckEditEmpty(edit_nextstep)) {
					return false;
				}	
			}
		
			if (!PictureButton_myself.IsExist()) {
				Utility.MessageBox( this,PictureButton_myself.FIELD );
				return false;
			}
			if (!Utility.isOpenNetwork()) {
				Utility.MessageBox(this,"打卡记录需要通过网络保存，请打开数据流量!");
				return false;
			}
//			Utility.MessageBox( "定位信息="+address );
			if ("".equals(address)|| address == null ) {
				Utility.MessageBox(this, "没有定位信息，请等待一会儿！" );
				return false;
			}
			else
				return true;
		}else {
			return false;
		}
	}
	@Override
	protected void onResume() {
		super.onResume();
		PictureButton_myself.postInvalidate();
		mMapView.onResume();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onPause() {
		super.onPause();
		mMapView.onPause();
//		deactivate();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onDestroy() {
		mLocClient.stop();
		mBaiduMap.setMyLocationEnabled(false);
		mMapView.onDestroy();
		mMapView = null;
		super.onDestroy();
	}

}
